package com.longsunhd.yum.buffalo.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.gg.reader.api.protocol.gx.LogBaseEpcInfo;
import com.longsunhd.yum.buffalo.R;
import com.longsunhd.yum.buffalo.base.BaseActivity;
import com.longsunhd.yum.buffalo.bean.BaffaloDetailBean;
import com.longsunhd.yum.buffalo.bean.LoginBean;
import com.longsunhd.yum.buffalo.bean.UserInfoBean;
import com.longsunhd.yum.buffalo.constant.Constant;
import com.longsunhd.yum.buffalo.eventbus.BaseEvent;
import com.longsunhd.yum.buffalo.eventbus.EpcInfoEvent;
import com.longsunhd.yum.buffalo.network.action.BaffaloApiUtils;
import com.longsunhd.yum.buffalo.network.action.UserApiUtils;
import com.longsunhd.yum.buffalo.util.ActivitySkipUtil;
import com.longsunhd.yum.buffalo.util.RfidReaderUtls;
import com.longsunhd.yum.buffalo.util.StatusBarUtil;
import com.longsunhd.yum.buffalo.util.ToastUtils;
import com.longsunhd.yum.buffalo.util.ViewUtils;
import com.longsunhd.yum.buffalo.util.generator.UIGenerator;
import com.longsunhd.yum.buffalo.widget.nicespinner.ISpinnerName;
import com.longsunhd.yum.buffalo.widget.nicespinner.MaterialSpinner;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;

import butterknife.BindView;
import butterknife.OnClick;
import cc.fussen.cache.Cache;

import static com.longsunhd.yum.buffalo.constant.Constant.BuffaloId;
import static com.longsunhd.yum.buffalo.constant.Constant.UserID;

/**
 * 作者：黄宣淇
 * 时间：2021/5/7 0007
 * 如何代码没有备注，一个月后，只有你和上帝知道--鲁迅
 */
public class MainActivity extends BaseActivity {

    @Override
    protected int getContentView() {
        return R.layout.activity_my_main;
    }

    @BindView(R.id.mUserName)
    public TextView mUserName;
    @BindView(R.id.mll_buffalo_info)
    public ViewGroup mll_buffalo_info;
    @BindView(R.id.mll_action)
    public ViewGroup mll_action;
    @BindView(R.id.mSpinner)
    public MaterialSpinner mSpinner;

    private LoginBean loginBean;
    private int buffaloId=0;

    @Override
    protected boolean initBundle(Bundle bundle) {
        if (bundle != null)
            loginBean = (LoginBean) bundle.getSerializable(Constant.loginBean);
        return super.initBundle(bundle);
    }

    @Override
    protected void initWidget() {
        super.initWidget();
        //设置状态栏字体颜色
        StatusBarUtil.setLightMode(this);
        RfidReaderUtls.newInstance().init(this);
    }

    @Override
    public boolean useEventBus() {
        return true;//开启event总线
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void onEvent(BaseEvent baseEvent) {
        super.onEvent(baseEvent);
        if (baseEvent instanceof EpcInfoEvent) {
            EpcInfoEvent epcInfoEvent = (EpcInfoEvent) baseEvent;
            ToastUtils.showText(epcInfoEvent.getLogBaseEpcInfo().getEpc());
            /*获取牛只信息*/
            String epc = epcInfoEvent.getLogBaseEpcInfo().getEpc();
            if (!TextUtils.isEmpty(epc)) {
                BaffaloApiUtils.newInstance().getBuffalo(loginBean.getData().getToken_type() + " " + loginBean.getData().getAccess_token(),
                        epc,
                        new Handler() {
                            @SuppressLint("HandlerLeak")
                            @Override
                            public void handleMessage(Message msg) {
                                super.handleMessage(msg);
                                BaffaloDetailBean baffaloDetailBean = (BaffaloDetailBean) msg.obj;
                                BaffaloDetailBean.DataBean dataBean=baffaloDetailBean.getData();

                                if (dataBean != null) {

                                    SetBuffaloInfo(dataBean);

                                    //保存历史记录
                                    LinkedList<BaffaloDetailBean.DataBean> linkedList= Cache.with(mActivity).getCache(Constant.epc,LinkedList.class);
                                    if(linkedList!=null){
                                        Optional<BaffaloDetailBean.DataBean > optionalBaffaloDetailBean=
                                                linkedList.stream().filter(a->a.getId()==dataBean.getId()).
                                                        findAny();
                                        if(optionalBaffaloDetailBean!=null){

                                            optionalBaffaloDetailBean.ifPresent(linkedList::remove
                                            );
                                        }
                                    }else {
                                        linkedList=new LinkedList<>();
                                    }
                                    linkedList.addFirst(dataBean);
                                    Cache.with(mActivity).saveCache(Constant.epc,linkedList);

                                    mSpinner.setItems(linkedList);
                                    mSpinner.setSelectedIndex(0);
                                    final List<BaffaloDetailBean.DataBean > finalList=new ArrayList<>(linkedList);
                                    mSpinner.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener() {
                                        @Override
                                        public void onItemSelected(MaterialSpinner view, int position, long id, ISpinnerName item) {

                                            SetBuffaloInfo(finalList.get(position));
                                        }
                                    });


                                }

                            }
                        });
            }


        }
    }

    private void SetBuffaloInfo(BaffaloDetailBean.DataBean dataBean) {
        if(dataBean==null||dataBean.getId()<=0)return;
        buffaloId= dataBean.getId();
        mll_buffalo_info.setVisibility(View.VISIBLE);
        mll_action.setVisibility(View.VISIBLE);
        mll_buffalo_info.removeAllViews();
        /*名字*/
        String name = dataBean.getName();

        UIGenerator.GeneratorBuffaloDetailUI(mActivity,
                R.layout.layout_buffalo_info_item, mll_buffalo_info, "标识", name);

        /*品种*/
        String bread = dataBean.getBreed();

        UIGenerator.GeneratorBuffaloDetailUI(mActivity,
                R.layout.layout_buffalo_info_item, mll_buffalo_info, "品种", bread);

        /*牧场*/
        String meadow = dataBean.getMeadow();

        UIGenerator.GeneratorBuffaloDetailUI(mActivity,
                R.layout.layout_buffalo_info_item, mll_buffalo_info, "牧场", meadow);

        /*牛舍*/
        String barn = dataBean.getBarn();

        UIGenerator.GeneratorBuffaloDetailUI(mActivity,
                R.layout.layout_buffalo_info_item, mll_buffalo_info, "牛舍", barn);

        /*是否发情*/
        String estrus = dataBean.getEstrus();

        String estrusDate = dataBean.getEstrus_date();
        if (estrusDate == null) {
            UIGenerator.GeneratorBuffaloDetailUI(mActivity,
                    R.layout.layout_buffalo_info_item, mll_buffalo_info, "是否发情", estrus);
        } else {
            UIGenerator.GeneratorBuffaloDetailUI(mActivity,
                    R.layout.layout_buffalo_info_item, mll_buffalo_info, "发情日期", estrusDate);
        }



        /*状态*/
        String status = dataBean.getStatus();

        UIGenerator.GeneratorBuffaloDetailUI(mActivity,
                R.layout.layout_buffalo_info_item, mll_buffalo_info, "状态", status);

        /*健康*/
        String health = dataBean.getHealth();

        UIGenerator.GeneratorBuffaloDetailUI(mActivity,
                R.layout.layout_buffalo_info_item, mll_buffalo_info, "健康", health);

        /*生日*/
        String birthday = dataBean.getBirthday();

        UIGenerator.GeneratorBuffaloDetailUI(mActivity,
                R.layout.layout_buffalo_info_item, mll_buffalo_info, "生日", birthday);

        /*性别*/
        String gender = dataBean.getGender();

        UIGenerator.GeneratorBuffaloDetailUI(mActivity,
                R.layout.layout_buffalo_info_item, mll_buffalo_info, "性别", gender);

        /*入栏时间*/
        String lairage_date = dataBean.getLairage_date();

        UIGenerator.GeneratorBuffaloDetailUI(mActivity,
                R.layout.layout_buffalo_info_item, mll_buffalo_info, "入栏时间", lairage_date);

        /*当前体重*/
        String current_weight = dataBean.getCurrent_weight();

        UIGenerator.GeneratorBuffaloDetailUI(mActivity,
                R.layout.layout_buffalo_info_item, mll_buffalo_info, "当前体重", current_weight);
        /*最初体重*/
        String init_weight = dataBean.getInit_weight();

        UIGenerator.GeneratorBuffaloDetailUI(mActivity,
                R.layout.layout_buffalo_info_item, mll_buffalo_info, "最初体重", init_weight);

        /*备注*/
        String remark = dataBean.getRemark();

        UIGenerator.GeneratorBuffaloDetailUI(mActivity,
                R.layout.layout_buffalo_info_item, mll_buffalo_info, "备注", remark);
    }

    @Override
    protected void initData() {
        super.initData();
        /*读取缓存值*/
        if (loginBean == null) {
            /*不是从登录页跳转过来的*/
            loginBean = Cache.with(MainActivity.this).getCache(Constant.UserInfoBean, LoginBean.class);
        }

        if (loginBean != null && loginBean.getData() != null) {
            getUserInfo(loginBean);
        } else {
            ActivitySkipUtil.skipAnotherActivity(this, LoginActivity.class, true);

        }
        initHistoryData();
        // onYearMonthDayTimePicker(mUserName);
    }

    private void initHistoryData() {
        //保存历史记录
        LinkedList<BaffaloDetailBean.DataBean> linkedList= Cache.with(mActivity).getCache(Constant.epc,LinkedList.class);
        if(linkedList==null)linkedList=new LinkedList<>();
        BaffaloDetailBean.DataBean dataBean=new BaffaloDetailBean.DataBean();
        dataBean.setName("查看牛信息历史记录");dataBean.setId(0);
        linkedList.addFirst(dataBean);
        mSpinner.setItems(linkedList);
        mSpinner.setSelectedIndex(0);
        final List<BaffaloDetailBean.DataBean > finalList=new ArrayList<>(linkedList);
        mSpinner.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener() {
            @Override
            public void onItemSelected(MaterialSpinner view, int position, long id, ISpinnerName item) {
                SetBuffaloInfo(finalList.get(position));
            }
        });
    }


    private void getUserInfo(LoginBean loginBean1) {
        loginBean = loginBean1;
        UserApiUtils.newInstance().getUserInfo(loginBean.getData().getToken_type() + " " + loginBean.getData().getAccess_token(),
                new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        super.handleMessage(msg);
                        try {
                            UserInfoBean userInfoBean = (UserInfoBean) msg.obj;

                            loginBean.getData().setName(userInfoBean.getData().getName());
                            mUserName.setText("当前用户：" + userInfoBean.getData().getName());
                            Cache.with(MainActivity.this).saveCache(Constant.UserInfoBean, loginBean);


                        } catch (Exception e) {
                            ActivitySkipUtil.skipAnotherActivity(MainActivity.this, LoginActivity.class, true);
                        }


                    }
                });
    }

    /*退出登录*/
    @OnClick(R.id.mLoginOut)
    public void mLoginOut() {
        try {
            ActivitySkipUtil.skipAnotherActivity(this, LoginActivity.class, true);
            Cache.with(MainActivity.this).saveCache(Constant.UserInfoBean, new LoginBean());
        } catch (Exception e) {
            e.getMessage();
        }
    }
    /*产奶*/
    @OnClick(R.id.bt_cnjl)
    public void bt_cnjl() {
        ActivitySkipUtil.skipAnotherActivity(this, MilkingRecordActivity.class, false);
    }
    /*用药记录*/
    @OnClick(R.id.bt_yygl)
    public void bt_yygl() {
        HashMap<String ,Object> hashMap=new HashMap<>();
        hashMap.put(BuffaloId,buffaloId);
        ActivitySkipUtil.skipAnotherActivity(this, MedicationActivity.class, hashMap,false);
    }

    @OnClick(R.id.mBtReadCard)
    public void mBtReadCard() {
        RfidReaderUtls.newInstance().readCard(RfidReaderUtls.C6, RfidReaderUtls.sinal);
    }

}
